package com.qqtop10.manager.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.qqtop10.manager.model.Admin;
import com.qqtop10.manager.model.AlipayBill;
import com.qqtop10.manager.model.Order;
import com.qqtop10.manager.model.Points;
import com.qqtop10.manager.model.Shop;
import com.qqtop10.manager.service.AlipayBillService;
import com.qqtop10.manager.service.OrderDetailedService;
import com.qqtop10.manager.service.OrderService;
import com.qqtop10.manager.service.PointsService;
import com.qqtop10.manager.service.ShopService;
import com.qqtop10.manager.utils.LogHelper;
import com.qqtop10.manager.utils.RandomUtils;
import com.qqtop10.manager.utils.Result;
import com.qqtop10.manager.utils.UrlPath;

/**
 * 订单管理控制器
 * 
 * @author ChenXinwei
 * 
 */
@RequestMapping("/manager/order")
@Controller
public class OrderController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;

	@Autowired
	@Qualifier("orderDetailedService")
	private OrderDetailedService orderDetailedService;

	@Autowired
	private PointsService pointsService;

	@Autowired
	private ShopService shopService;
	
	@Autowired
	@Qualifier("alipayBillService")
	private AlipayBillService alipayBillService;

	public static final Map<String, Object> p = new HashMap<>();

	/**
	 * 条件性获取订单信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getOrderListBySelective.do")
	public void getOrderListBySelective(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		Map<String, Object> map = new HashMap<>();
		StringBuffer where = null;
		String orderId = null;
		String shop_name = null;
		String nickname = null;
		String status = null;
		try {
			orderId = request.getParameter("orderId");
			shop_name = request.getParameter("shop_name");
			nickname = request.getParameter("nickname");
			status = request.getParameter("status");
			where = new StringBuffer();
			// 必须是未删除的
			where.append("WHERE tbo.isdeleted = 0");
			// 如果订单号不为空
			if (orderId != null && !"".equals(orderId)) {
				where.append(" AND tbo.orderid = '" + orderId + "'");
			}
			// 如果商店名称不为空
			if (shop_name != null && !"".equals(shop_name)) {
				where.append(" AND tbs.name LIKE '%" + shop_name + "%'");
			}
			// 如果昵称不为空
			if (nickname != null && !"".equals(nickname)) {
				where.append(" AND tbu.nickname LIKE '%" + nickname + "%'");
			}
			// 如果状态不为空
			if (status != null && !"".equals(status)) {
				where.append(" AND tbo.status = " + status);
			}
			map.put("order", " ORDER BY id DESC ");
			map.put("where", where);
			map.put("tb_shop", "tb_shop");
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.getWriter().print(super.page(map, orderService, request));

	}

	/**
	 * 条件性获取订单详细信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getOrderDetailedByUuid.do")
	public void getOrderDetailedByUuid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		Map<String, Object> map = new HashMap<>();
		// 获取商品uuid
		String uuid = request.getParameter("uuid");
		StringBuffer where = new StringBuffer();
		// 必须是未删除的
		where.append("WHERE tbod.isdeleted = 0 ");
		where.append("AND tbod.order_uuid = '" + uuid + "'");
		map.put("where", where);
		response.getWriter().print(
				super.page(map, orderDetailedService, request));
	}

	/**
	 * 条件性获取订单信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getRefundOrderList.do")
	public void getRefundOrderList(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		Map<String, Object> map = new HashMap<>();
		StringBuffer where = null;
		String orderId = null;
		try {
			orderId = request.getParameter("orderId");
			where = new StringBuffer();
			// 必须是未删除的
			where.append("WHERE tbo.isdeleted = 0");
			// 如果订单号不为空
			if (orderId != null && !"".equals(orderId)) {
				where.append(" AND tbo.orderid = '" + orderId + "'");
			}
			// 状态为5的订单
			where.append(" AND tbo.status = 5");
			map.put("order", " ORDER BY id DESC ");
			map.put("where", where);
			map.put("tb_shop", "tb_shop");
		} catch (Exception e) {
			e.printStackTrace();
		}
		String r= super.page(map, orderService, request);
		response.getWriter().print(r);

	}

	/**
	 * 拒绝退款
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("refusedRefund.do")
	public void refusedRefund(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/javascript; charset=utf-8");
		String callback = request.getParameter("callback");
		Result result = new Result();
		// 获取订单uuid
		String orderUuid = request.getParameter("uuid");
		Order order = null;
		try {
			order = orderService.selectByUuid(orderUuid);
			// 恢复状态
			int status = order.getStatus();
			order.setStatus(order.getOld_status());
			order.setOld_status(status);
			int i = orderService.updateByUuidSelective(order);
			if (i > 0) {
				logger.info("已拒绝退款申请");
				result.setCode(1);
				Admin Tempadmin = (Admin) getRequest().getSession().getAttribute("Logind");
				LogHelper.Log(Tempadmin.getAccount(),"后台订单管理模块","拒绝退款申请成功",LogHelper.getLocalIp(getRequest()),Tempadmin.getAccount(),"",true);

				result.setMsg("已拒绝退款申请");
			} else {
				logger.info("拒绝退款申请失败：可能参数错误");
				result.setCode(99);
				result.setMsg("拒绝退款申请失败：可能参数错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("拒绝退款申请失败：" + e.getMessage());
			result.setCode(500);
			result.setMsg("拒绝退款申请失败：" + e.getMessage());
		}
		response.getWriter().print(super.result2Json(result, callback));

	}

	/**
	 * 同意退款
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("agreedRefund.do")
	public void agreedRefund(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");
		String callback = request.getParameter("callback");
		Result result = new Result();
		// 获取订单uuid
		String orderUuid = request.getParameter("uuid");
		
		Order order = orderService.selectByUuid(orderUuid);
		if (order == null) {
			result.setCode(99);
			result.setMsg("操作失败：订单不存在");
			return;
		}
		if (order.getStatus() != 5) {
			result.setCode(99);
			result.setMsg("操作失败：订单不符合退款要求");
			return;
		}
		// 批次号
		String batch_no = "";
		try {
			
			
			result.setCode(1);
			result.setMsg("操作成功：退款成功");
			logger.info("操作成功：退款成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("操作失败：" + e.getMessage());
			result.setCode(500);
			result.setMsg("操作失败：" + e.getMessage());
			// 出错将其移除
			p.remove(batch_no);
		}
		response.getWriter().print(super.result2Json(result, callback));

	}

	/**
	 * 转账/付款
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("transfer.do")
	public void transfer(HttpServletRequest request,
			HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");
		Result result = new Result();
		// 获取订单uuid
		String orderUuid = request.getParameter("uuid");
		Order order = orderService.selectByUuid(orderUuid);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		DecimalFormat df = new DecimalFormat("#.00");
		String batch_no = "";
		if (order == null) {
			result.setCode(99);
			result.setMsg("操作失败：订单不存在");
			return;
		}
		if (order.getPay_seller_status()) {
			result.setCode(99);
			result.setMsg("操作失败：订单已付款");
			return;
		}

		// 根据订单获取商店信息
		Shop shop = shopService.selectByUuid(order.getShop_uuid());

		// //////////////////////////////////请求参数//////////////////////////////////////

		try {
			// 转账扣除点数
			Points points = pointsService.getPoints();
			// 服务器异步通知页面路径
			String notify_url = UrlPath.transferNotifyUrl;
			// 需http://格式的完整路径，不允许加?id=123这类自定义参数

			// 付款账号
			String email = AlipayConfig.seller_email;
			// 必填

			// 付款账户名
			String account_name = AlipayConfig.seller_name;
			// 必填，个人支付宝账号是真实姓名公司支付宝账号是公司名称

			// 付款当天日期
			String pay_date = sdf.format(date);
			// 必填，格式：年[4位]月[2位]日[2位]，如：20100801

			// 批次号
			batch_no = sdf.format(date) + RandomUtils.makeRandomDigit6();
			// 必填，格式：当天日期[8位]+序列号[3至16位]，如：201008010000001
			// 保存该退款号的订单uuid
			//p.put(batch_no, order.getUuid());
			alipayBillService.add(new AlipayBill(null, batch_no, order.getUuid()));
			// 付款总金额
			String batch_fee = df.format(order.getActual_price()
					- order.getActual_price() * (points.getPoints() / 100));
			// 必填，即参数detail_data的值中所有金额的总和

			// 付款笔数
			String batch_num = "1";
			// 必填，即参数detail_data的值中，“|”字符出现的数量加1，最大支持1000笔（即“|”字符出现的数量999个）

			// 付款详细数据
			String detail_data = batch_no + "1^" + shop.getAlipay() + "^"
					+ shop.getContacts() + "^" + batch_fee + "^付款给："
					+ shop.getName();
			// 必填，格式：流水号1^收款方帐号1^真实姓名^付款金额1^备注说明1|流水号2^收款方帐号2^真实姓名^付款金额2^备注说明2....

			// ////////////////////////////////////////////////////////////////////////////////

			// 把请求参数打包成数组
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "batch_trans_notify");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			sParaTemp.put("notify_url", notify_url);
			sParaTemp.put("email", email);
			sParaTemp.put("account_name", account_name);
			sParaTemp.put("pay_date", pay_date);
			sParaTemp.put("batch_no", batch_no);
			sParaTemp.put("batch_fee", batch_fee);
			sParaTemp.put("batch_num", batch_num);
			sParaTemp.put("detail_data", detail_data);
			sParaTemp.put("sign_type", AlipayConfig.sign_type);
			sParaTemp.put("sign", AlipayConfig.sign);

			/*System.out.println("---------------------------------");
			for (String key : sParaTemp.keySet()) {
				System.out.println("key:" + key + ",value:"
						+ sParaTemp.get(key));
			}
			System.out.println("---------------------------------");*/

			// 建立请求
			String sHtmlText = AlipaySubmit
					.buildRequest(sParaTemp, "get", "确认");
			response.getWriter().print(sHtmlText);
			result.setCode(1);
			result.setMsg("操作成功：已向支付宝发出付款申请");
			logger.info("操作成功：已向支付宝发出付款申请");
		} catch (Exception e) {
			e.printStackTrace();
			// 出错将其移除
			//p.remove(batch_no);
		}

	}
	

}
